﻿var sohavideo = function ($) {
    var settings = {
        highlightPlayerId: "object_Kenh14",
        highlightEmbedCodePlaceHolderElement: "#video-embeb",
        highlightTitleElement: '#video-title',
        highlightSapoElement: '#video-description',
        highlightTagsElement: '#video-tags',
        highlightLikePlaceHolderElement: '#video-like',
        highlightSharePlaceHolderElement: '#video-share',
        highlightListPlaceHolder: '#divPlaylistVideo',

        listPlaceHolder: '#video-list-content',
        listPagingPlaceHolder: '#video-paging',
        lbSlideContentPlaceHolder: "#lb-slide",

        lbPlayerId: "object_Kenh14_lb",
        lbEmbedCodePlaceHolderElement: "#lb-video-embed",
        lbTitleElement: '#lb-video-title',
        lbSapoElement: '#lb-video-description',
        lbTagsElement: '#lb-video-tags',
        lbLikePlaceHolderElement: '#lb-video-like',
        lbSharePlaceHolderElement: '#lb-video-share',
        lbListPlaceHolder: '#divPlaylistVideo',
        lbDivCommentId: 'mingid_comments_content',

        domain: "http://soha.vn",
        videoImageDomain: "http://video-thumbs.vcmedia.vn",
        videoWidth: 606,
        videoHeight: 357,
        pageSize: 16,
        classId: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
        //map với các trường trong sql
        id: "Id",
        title: "Name",
        url: "Url",
        description: "Description",
        avatar: "Avatar",
        videoKey: "KeyVideo",
        zoneId: "ZoneId",
        name: "Name",
        playerName: "PName",
        tags: "Tags",
        publishDate: "PublishDate",
        distributionDate: "DistributionDate",
        mp4Url: "Mp4Url"

    };

    var cache = new Array();
    var currentData = null;
    var isLoading = false;
    var baseurl = document.location.href;
    var basetitle = document.title;
    var onCloseCallback = new Array();


    //build absoluteurl
    function buildAbsoluteUrl(url) {
        if (url.indexOf("http") != -1) {
            return url;
        }
        return String.format("{0}{1}", settings.domain, url);
    }

    function buildSortUrl(video) {
        return buildAbsoluteUrl(String.format("/video-{0}.htm", video[settings.id]));
    }

    function initComment(sortUrl, detailedUrl, encodedBase64Name, divCommentId) {
        var width = "100%";
        var appKey = "b88af5f35d5e00c948ae2bda2d867590";
        var numCount = 5;
        var debugCache = 1;
        var min = 0;
        var scroll = 0;
        var verify = 0;
        var verifyFlag = 0;
        var iframeSourceFormat = "http://comment.vietid.net/comments?app_key={0}&content_url={1}&news_title={2}&num_count={3}&debugcache={4}&min={5}&scroll={6}&http_referer={7}&verify={8}&verify_flag={9}";

        var iframeSource = String.format(iframeSourceFormat, appKey, sortUrl, encodedBase64Name, numCount, debugCache, min, scroll, detailedUrl, verify, verifyFlag);

        var mingidIfr = document.createElement('iframe');
        mingidIfr.setAttribute('width', width);
        mingidIfr.setAttribute('height', 238);
        mingidIfr.setAttribute('border', 'medium none');
        mingidIfr.setAttribute('overflow', 'hidden');
        mingidIfr.setAttribute('scrolling', 'no');
        mingidIfr.setAttribute('frameborder', '0');
        mingidIfr.setAttribute('id', 'mingid_comment_iframe');
        mingidIfr.setAttribute('src', iframeSource);
        $('#' + divCommentId).empty().append(mingidIfr);
    }

    function thumb_zoom(url, width, height) {
        if (url.indexOf("http:") != -1 || url.indexOf("https:") != -1) {
            if (url.indexOf(settings.videoImageDomain) != -1) {
                url = url.replace(settings.videoImageDomain, '');
            }
            else {
                return url;
            }
        }
        return String.format('{0}/zoom/{1}_{2}/{3}', settings.videoImageDomain.trimEnd('/'), width, height, url.trimStart('/'));
    }

    function getSouceAvatar(url) {
        if (url.indexOf("http:") != -1 || url.indexOf("https:") != -1) {
            if (url.indexOf(settings.videoImageDomain) != -1) {
                url = url.replace(settings.videoImageDomain, '');
            }
            else {
                return url;
            }
        }
        return String.format('{0}/{1}', settings.videoImageDomain.trimEnd('/'), url.trimStart('/'));
    }

    function thumb_w(url, width) {
        if (url.indexOf("http:") != -1 || url.indexOf("https:") != -1) {
            if (url.indexOf(settings.videoImageDomain) != -1) {
                url = url.replace(settings.videoImageDomain, '');
            }
            else {
                return url;
            }
        }
        return String.format('{0}/thumb_w/{1}/{2}', settings.videoImageDomain.trimEnd('/'), width, url.trimStart('/'));
    }

    //like
    function buildLikeButton(url, showFace) {
        url = buildAbsoluteUrl(url);
        return String.format("<iframe src=\"http://www.facebook.com/plugins/like.php?href={0}&amp;layout={2}&amp;show_faces={1}&amp;action=like&amp;colorscheme=light&amp;send=true\" scrolling=\"no\" frameborder=\"0\" allowtransparency=\"true\"></iframe>", url, showFace, showFace ? "standard" : "button_count");
    }

    //share 
    function buildShareButton(url) {
        url = buildAbsoluteUrl(url);
        return String.format("<a class=\"sharefacebook\" href=\"http://www.facebook.com/sharer.php?u={0}\" target=\"_blank\"></a>", url);
    }

    function isTablet() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
    }

    //build embedcode
    function buildEmbedCode(id, key, name, width, height) {
        var sb = '';
        var videoUrl = String.format("http://cache.hosting.vcmedia.vn/?key={0}&amp;pname={1}", key, name);

        sb += String.format("<object width=\"{0}\" height=\"{1}\" classid=\"{2}\" id=\"{3}\">", width, height, settings.classId, id);
        sb += "<param name=\"wmode\" value=\"transparent\">";
        sb += String.format("<param name=\"movie\" value=\"{0}\">", videoUrl);
        sb += "<param name=\"allowFullScreen\" value=\"true\">";
        sb += "<param name=\"flashvars\" value=\"videotag=true&autostart=true\">";
        sb += "<param name=\"allowscriptaccess\" value=\"always\">";
        sb += "<param name=\"bgcolor\" value=\"#000000\">";
        sb += String.format("<embed width=\"{0}\" height=\"{1}\"  src=\"{2}\"  id=\"{3}\" name=\"movie\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" wmode=\"transparent\" flashvars=\"videotag=true&autostart=true\" bgcolor=\"#000000\" quality=\"high\"></object>",
                            width, height, videoUrl, id);
        return sb;
    }

    function buildMp4EmbedCode(mp4Url, avatar, width, height) {
        //console.log(mp4Url);
        return String.format("<video width=\"{0}\" height=\"{1}\" poster=\"{2}\" controls=\"controls\"><source src=\"{3}\" type=\"video/mp4;codecs=&quot;avc1.42E01E, mp4a.40.2&quot;\" />Trình duyệt của bạn chưa hỗ trợ thẻ này.</video>",
                width,
                height,
                avatar,
                mp4Url
            );
    }

    function closeLightbox() {
        $('.video-menu .active').click();
        $('html,body').removeClass('no-scroll');
        $(settings.lbEmbedCodePlaceHolderElement).empty();
        toggleLightbox();
        pushState(baseurl, basetitle);
        resume(settings.highlightPlayerId);
        if (onCloseCallback && onCloseCallback.length > 0) {
            for (var i = 0; i < onCloseCallback.length; i++) {
                execCallback(onCloseCallback[i]);
            }
        }
    }

    function toggleLightbox() {
        $('.lb-background').fadeToggle();
    }

    function pushState(url, title) {
        if (history && history.pushState) {
            window.history.pushState('', '', url);
            document.title = title;
        }
    }

    function pause(playerId) {
        try {
            var player = getPlayer(playerId);
            if (player != null)
                player.openlb();
        } catch (e) { };
    }

    function resume(playerId) {
        try {
            var player = getPlayer(playerId);
            if (player != null) {
                player.closelb();
                player.resumeVideo();
            }
        } catch (e) { };
    }

    //get player
    function getPlayer(playerId) {
        //chrome,firefox
        if (document.embeds[playerId]) {
            return document.embeds[playerId];
        }
        //ie
        return document.getElementById(playerId);
    }

    //execute Callback
    function execCallback(callback) {
        if (typeof (callback) == "function") {
            return callback();
        }
        return false;
    }

    //get cache
    function getCache(cacheKey) {
        return cache[cacheKey];
    }

    //set cache
    function setCache(cacheKey, data) {
        cache[cacheKey] = data;
        return;
    }

    //get cachekey
    function getCacheKey(functionName, args) {
        return String.format("{0}_{1}", functionName, args.join('_'));
    }

    //get highlight video by videoid ( from jsCache )
    function getVideoDetail(videoId) {
        var cacheKey = getCacheKey("getVideoDetail", [videoId]);
        var result = getCache(cacheKey);
        if (result == null) {
            if (currentData && currentData.length > 0) {
                for (var i = 0; i < currentData.length; i++) {
                    if (currentData[i][settings.id] == videoId) {
                        result = currentData[i];
                        setCache(cacheKey, result);
                        break;
                    }
                }
            }
        }
        return result;
    }

    //set highlight video
    function setHilightVideo(video, width, height) {
        if (isTablet()) {
            var embedCode = buildMp4EmbedCode(video[settings.mp4Url], getSouceAvatar(video[settings.avatar]), width, height);
            $(settings.highlightEmbedCodePlaceHolderElement).html(embedCode);
        } else {
            getPlayer(settings.highlightPlayerId).callnext(video[settings.videoKey]);
        }
        $(settings.highlightTitleElement).text(video[settings.title]);
        $(settings.highlightSapoElement).text(video[settings.description]);
        $(settings.highlightTagsElement).html(video[settings.tags]);
        $(settings.highlightLikePlaceHolderElement).html(buildLikeButton(video[settings.url], true));
        $(settings.highlightSharePlaceHolderElement).html(buildShareButton(video[settings.url]));
    }

    function lightboxVideo(video, callback) {
        pause(settings.highlightPlayerId);
        var embedCode = buildEmbedCode(settings.lbPlayerId, video[settings.videoKey], video[settings.playerName], settings.videoWidth, settings.videoHeight);
        $(settings.lbEmbedCodePlaceHolderElement).html(embedCode);
        $(settings.lbTitleElement).text(video[settings.title]);
        $(settings.lbSapoElement).text(video[settings.description]);
        if (video[settings.tags] != '') {
            $(settings.lbTagsElement).html(video[settings.tags]);
            $(settings.lbTagsElement).parent().show();
        } else {
            $(settings.lbTagsElement).parent().hide();
        };
        $(settings.lbLikePlaceHolderElement).html(buildLikeButton(video[settings.url], false));
        $(settings.lbSharePlaceHolderElement).html(buildShareButton(video[settings.url]));
        pushState(video[settings.url], formatString("{0} | soha.vn", video[settings.title]));
        initComment(buildSortUrl(video), buildAbsoluteUrl(video[settings.url]), $.base64Encode(encodeURI(video[settings.title])), settings.lbDivCommentId);
        if (!$('html, body').hasClass('no-scroll')) {
            toggleLightbox();
            $('html,body').addClass('no-scroll');
        }
        execCallback(callback);
    }



    function showLightboxSlide(json, callback, viewMoreUrl) {

        if (json == null) {
            json = currentData;
        }
        if (json && json.length > 0) {
            var html = '';
            var width = 170; //113;
            var height = 100; //65;
            var format = "<li><a href='{0}' rel='{3}'><img src='{2}' /></a><h2><a rel='{3}' href='{0}'>{1}</a></h2></li>";
            for (var i = 0; i < json.length; i++) {
                var item = json[i];

                var avatar = thumb_zoom(item[settings.avatar], width, height);
                html += formatString(format, item[settings.url], item[settings.title], avatar, item[settings.id]);
            }
            html += formatString(format, viewMoreUrl, "", "/Images/morevideo.png", -1);

            $(settings.lbSlideContentPlaceHolder).html(html);
            $('.lb-slide ul li').addClass('mcgSlideItem');
            $('.lb-slide ul li:last').addClass("last");
            var numberOfVisibleSlide = Math.floor((getViewPortWidth() - 100) / $('.lb-slide ul li:first').innerWidth());
            $(settings.lbSlideContentPlaceHolder).mcgSlider({
                numberOfVisibleSlides: numberOfVisibleSlide,
                nextButton: $('.lb-slide-nav.nav-next'),
                preButton: $('.lb-slide-nav.nav-prev'),
                auto: false,
                autoWidth: true
            });


            $('.lb-slide ul li a').each(function () {
                $(this).unbind('click').bind('click', function (e) {
                    var handler = $(this);
                    var videoId = parseInt(handler.attr('rel'));
                    if (videoId > 0) {
                        e.preventDefault();
                        var video = getVideoDetail(videoId);
                        lightboxVideo(video, function () {
                            $('.lb-slide ul li.current').removeClass('current');
                            handler.closest("li").addClass('current');

                        });
                    }
                });
            });

            $('.lb-slide ul li').height(function () {
                var maxHeight = 0;
                $('.lb-slide ul li').each(function () {
                    if (maxHeight < $(this).height()) {
                        maxHeight = $(this).height();
                    }
                });
                return maxHeight;
            });
            execCallback(callback);
        }
    }

    //load newest video by zone for lightbox
    function loadNewestVideoForLightbox(zoneId, pageIndex, pageSize, callback, viewMoreUrl) {
        var cacheKey = getCacheKey("NewestVideo", [zoneId, pageIndex, pageSize]);
        var videos = getCache(cacheKey);
        if (videos && videos.length > 0) {
            showLightboxSlide(videos,
                function () {
                    currentData = videos;
                    execCallback(callback);
                }, viewMoreUrl);
            return;
        }
        isLoading = true;
        $.ajax({
            url: "/Services/Video/GetNewestVideoByZone.ashx",
            data: { zoneId: zoneId, pageIndex: pageIndex, pageSize: pageSize },
            dataType: "json",
            success: function (response) {
                setCache(cacheKey, response);
                currentData = response;
                showLightboxSlide(response, function () {
                    execCallback(callback);
                    isLoading = false;
                }, viewMoreUrl);
            }
        });
    }

    //load new video by zone
    function loadNewestVideo(zoneId, pageIndex, pageSize, callback) {
        var cacheKey = getCacheKey("NewestVideo", [zoneId, pageIndex, pageSize]);
        var videos = getCache(cacheKey);
        if (videos && videos.length > 0) {
            bindListVideo(videos, callback);
            return;
        }
        isLoading = true;
        $.ajax({
            url: "/Services/Video/GetNewestVideoByZone.ashx",
            data: { zoneId: zoneId, pageIndex: pageIndex, pageSize: pageSize },
            dataType: "json",
            success: function (response) {
                setCache(cacheKey, response);
                bindListVideo(response, function () {
                    execCallback(callback);
                    isLoading = false;
                });
            }
        });
    }

    //load most view video by zone
    function loadMostViewVideo(zoneId, pageIndex, pageSize, callback) {
        var cacheKey = getCacheKey("MostViewVideo", [zoneId, pageIndex, pageSize]);
        var videos = getCache(cacheKey);
        if (videos && videos.length > 0) {
            bindListVideo(videos, callback);
            return;
        }
        isLoading = true;
        $.ajax({
            url: "/Services/Video/GetMostViewVideoByZone.ashx",
            data: { zoneId: zoneId, pageIndex: pageIndex, pageSize: pageSize },
            dataType: "json",
            success: function (response) {
                setCache(cacheKey, response);
                bindListVideo(response, function () {
                    execCallback(callback);
                    isLoading = false;
                });
            }
        });
    }

    function bindListVideo(json, callback) {
        if (json != null && json.length > 0) {
            currentData = json;
            var html = '';
            var imageWidth = 170;
            var imageHeight = 100;
            var itemFormat = "<div rel=\"{4}\" class=\"video-item\"><a href=\"{0}\"><img src=\"{2}\" title=\"{1}\" /></a><div class=\"video-info\"><div class=\"like-facebook\">{3}</div></div><h4><a href=\"{0}\">{1}</a></h4></div>";
            var buttonLikeFormat = "<iframe src=\"//www.facebook.com/plugins/like.php?locale=vi_VN&amp;href={0}&amp;send=false&amp;layout=button_count&amp;width=84&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=24&amp;appId=433277336731778\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:84px; height:21px;\" allowtransparency=\"true\"></iframe>";
            for (var i = 0; i < json.length; i++) {
                var video = json[i];
                var likeButton = String.format(buttonLikeFormat, buildAbsoluteUrl(video[settings.url]));
                var avatar = thumb_zoom(video[settings.avatar], imageWidth, imageHeight);
                html += String.format(itemFormat, video[settings.url], video[settings.title], avatar, likeButton, video[settings.id]);
            }
            $(settings.listPlaceHolder).html(html);
            var videoItems = $(settings.listPlaceHolder).find(".video-item");
            var seperator = "<div class=\"video-sapatator\"></div>";
            videoItems.each(function () {
                $(this).on('click', function (e) {
                    e.preventDefault();
                    sohavideo.lightboxVideo(parseInt($(this).attr("rel")));
                });
                $(this).find("img:first").after("<img src=\"http://kenh143.vcmedia.vn/skin/listvideo/video-view-icon.png\" class=\"icon-video\">");
                if ((videoItems.index($(this)) + 1) % 4 === 0) {
                    $(this).addClass("video-item-last").after(seperator);
                }
            });
            bindListHighlightVideo(json);
            execCallback(callback);
        }
    }

    function bindListHighlightVideo(json) {
        if (json != null && json.length > 0) {
            var itemFormat = "<li rel=\"{3}\"><a class=\"link-img\" href=\"{0}\"><img id=\"imgplaylist\" src=\"{2}\" /></a><a class=\"lnk\" href=\"{0}\">{1}</a></li>";
            var html = '';
            var imageWidth = 53;
            var imageHeight = 33;
            for (var i = 0; i < json.length; i++) {
                var video = json[i];
                html += String.format(itemFormat, video[settings.url], video[settings.title], thumb_zoom(video[settings.avatar], imageWidth, imageHeight), video[settings.id]);
            }

            $(settings.highlightListPlaceHolder).html(html);

            $(settings.highlightListPlaceHolder).find("li").each(function () {
                $(this).unbind('click').bind('click', function (e) {
                    e.preventDefault();
                    var videoId = $(this).attr("rel");
                    sohavideo.highlightVideo(videoId);
                    $(settings.highlightListPlaceHolder).find("li.current").removeClass("current");
                    $(this).addClass("current");
                });
            });

            var iconVideo = "<img src=\"/Images/VideoImages/video-small-icon.png\" class=\"icon-video\">";
            var txtNowPlaying = "<p class=\"video-play-status\">Now playing</p>";
            $(settings.highlightListPlaceHolder + " a.link-img").each(function () {
                $(this).append(iconVideo).after(txtNowPlaying);
            });
        }
    }

    function unsyncPaging(zoneId, pageIndex, pageSize, url, callback) {
        var cacheKey = getCacheKey('countVideoByZone', [zoneId, pageIndex, pageSize, url]);
        var numberOfVideo = getCache(cacheKey);
        var sumPage;
        if (numberOfVideo != null) {
            sumPage = Math.floor(numberOfVideo / pageSize);
            return paging(pageIndex, sumPage, url, callback);
        }
        $.ajax({
            url: '/Services/Video/CountVideoByZone.ashx',
            data: { zoneId: zoneId },
            success: function (response) {
                numberOfVideo = parseInt(response);
                setCache(cacheKey, numberOfVideo);
                sumPage = Math.floor(numberOfVideo / pageSize);
                paging(pageIndex, sumPage, url, callback);
            }
        });
        return false;
    }

    function paging(pageIndex, sumPage, url, callback) {
        var html = '';
        var numberOfDisplayPage = 9;
        var contentPlaceHolder = $(settings.listPagingPlaceHolder);
        var startPage = Math.max(1, pageIndex - Math.floor(numberOfDisplayPage / 2));
        var endPage = Math.min(sumPage, pageIndex + Math.floor(numberOfDisplayPage / 2));
        if (pageIndex > 1 && startPage > 1) {
            html += buildLink(1, url, 'TRANG ĐẦU');
            html += buildLink(startPage - 1, url, '...');
        }
        for (var i = startPage; i <= endPage; i++) {
            html += buildLink(i, url, i, i === pageIndex ? 'active' : '');
        }
        if (pageIndex < sumPage && endPage < sumPage) {
            html += buildLink(endPage + 1, url, '...');
            html += buildLink(sumPage, url, 'TRANG CUỐI');
        }
        $(contentPlaceHolder).html(html);
        execCallback(callback);
    }

    function buildLink(pageIndex, url, text, cssClass) {
        var pagingUrl = 'javascript:void(0);'; //'#';//formatString('{0}page-{1}.htm', url, pageIndex);
        return formatString("<a href='{0}' class='{3}' title='trang {1}' rel='{1}'>{2}</a>", pagingUrl, pageIndex, text, cssClass);
    }

    function formatString(text) {
        if (arguments.length <= 1) {
            return text;
        }

        var tokenCount = arguments.length - 2;
        for (var token = 0; token <= tokenCount; token++) {
            text = text.replace(new RegExp("\\{" + token + "\\}", "gi"),
                                                arguments[token + 1]);
        }
        return text;
    }

    function scrollToList() {
        $('html,body').delay(1000).animate({ scrollTop: $(settings.listPlaceHolder).offset().top - 50 }, 'slow');
    }

    return {
        init: function (options) {
            $.extend(settings, options);
        },
        highlightVideo: function (videoId, width, height) {
            return setHilightVideo(getVideoDetail(videoId), width, height);
        },
        lightboxVideo: function (videoId, callback) {
            return lightboxVideo(getVideoDetail(videoId), function () {
                showLightboxSlide(null, function () {

                });
                execCallback(callback);
            });
        },
        setCurrentData: function (data) {
            currentData = data;
        },
        loadNewVideo: function (zoneId, pageIndex, pageSize, pagingUrl, callback) {
            if (callback == null)
                scrollToList();
            loadNewestVideo(zoneId, pageIndex, pageSize,
                function () {
                    unsyncPaging(zoneId, pageIndex, pageSize, pagingUrl, function () {
                        $(settings.listPagingPlaceHolder).find('a').each(function () {
                            $(this).attr('onclick', formatString("sohavideo.loadNewVideo({0},{1},{2},'{3}', null);", zoneId, $(this).attr('rel'), pageSize, pagingUrl));
                        });
                    });
                    execCallback(callback);
                });
        },
        loadMostViewVideo: function (zoneId, pageIndex, pageSize, pagingUrl, callback) {
            if (callback == null)
                scrollToList();
            loadMostViewVideo(zoneId, pageIndex, pageSize,
                function () {
                    unsyncPaging(zoneId, pageIndex, pageSize, pagingUrl, function () {
                        $(settings.listPagingPlaceHolder).find('a').each(function () {
                            $(this).attr('onclick', formatString("sohavideo.loadMostViewVideo({0},{1},{2},'{3}',null);", zoneId, $(this).attr('rel'), pageSize, pagingUrl));
                        });
                    });
                    execCallback(callback);
                });
        },
        loadNewVideoForLightbox: function (zoneId, pageIndex, pageSize, callback, viewMoreUrl) {
            return loadNewestVideoForLightbox(zoneId, pageIndex, pageSize, callback, viewMoreUrl);
        },
        closeLightbox: function () {
            return closeLightbox();
        },
        pushVideoToCache: function (video) {
            var cacheKey = getCacheKey("getVideoDetail", [video[settings.id]]);
            setCache(cacheKey, video);
        },
        onCloseLightbox: function (callback) {
            onCloseCallback.push(callback);
        },
        isTablet: function () {
            return isTablet();
        }
    };
} (jQuery);


 
 
 
